package com.gdufe.uaa.service;

import com.alibaba.fastjson.TypeReference;
import com.gdufe.common.feign.UserFeign;
import com.gdufe.common.utils.R;
import com.gdufe.uaa.entity.CustomUserDetails;
import com.gdufe.common.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名从数据库查询数据
        R r = userFeign.getUserByName(username);
        TypeReference<User> typeReference = new TypeReference<User>() {
        };
        User user = r.getData(typeReference);
        if (user == null) {
            return null;
        }

        //根据用户状态分配相应角色
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (user.getStatus() == 1) {
            //分配管理员角色
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            //分配用户角色
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        //创建用户详情信息
        CustomUserDetails customUserDetails = new CustomUserDetails();
        customUserDetails.setId(user.getId());
        customUserDetails.setUsername(username);
        customUserDetails.setPassword(user.getPassword());
        customUserDetails.setAuthorities(authorities);

        return customUserDetails;
    }
}
